package top.ddandang.blog.controller;


import top.ddandang.blog.bean.GlobalResponse;
import top.ddandang.blog.model.query.PageBean;
import top.ddandang.blog.service.CategoriesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author D
 * @since 2020-06-23
 */
@Slf4j
@RestController
@RequestMapping("/categories")
public class CategoriesController {

    @Resource
    private CategoriesService categoriesService;

    @PostMapping("/insertCategories")
    public GlobalResponse insertCategories(String name, String description) {
        categoriesService.insertCategories(name, description);
        return GlobalResponse.success().message("插入成功！");
    }

    @PostMapping("/insertCategoriesIncludeImages")
    public GlobalResponse insertCategoriesIncludeImages(MultipartFile file, String name, String description) {
        String imageUrl = categoriesService.insertCategoriesImage(file);
        categoriesService.insertCategories(name, description, imageUrl);
        return GlobalResponse.success().message("插入成功！");
    }

    @GetMapping("/listCategories")
    public GlobalResponse listCategories(@RequestParam(required = true) int pageNo,
                                         @RequestParam(required = true) int pageSize) {
        PageBean pageBean = new PageBean(pageNo, pageSize, 0);
        return GlobalResponse.success().data("categoriesList", categoriesService.listCategory(pageBean));
    }

    @GetMapping("/allCategories")
    public GlobalResponse allCategories() {
        return GlobalResponse.success().data("categoriesList", categoriesService.allCategory());
    }

    @PostMapping("/insertCategoryImages")
    public GlobalResponse insertCategoryImages(MultipartFile file, Integer categoryId) {
        String imageUrl = categoriesService.insertCategoriesImage(file);
        int flag = categoriesService.updateCategoryImage(categoryId, imageUrl);
        if(flag == 1){
            return GlobalResponse.success().data("imageUrl", imageUrl);
        }else {
            return GlobalResponse.failed();
        }

    }

    @PostMapping("/updateCategory")
    public GlobalResponse updateCategory(Integer categoryId, String name, String description) {

        int flag = categoriesService.updateCategory(categoryId, name, description);
        if(flag == 1){
            return GlobalResponse.success();
        }else {
            return GlobalResponse.failed();
        }
    }
}

